package com.szyt.basicframe.aspect;

import com.szyt.basicframe.annotation.RequiresPermissions;
import com.szyt.basicframe.common.Logical;
import com.szyt.basicframe.pojo.bo.LoginUser;
import com.szyt.basicframe.util.LoginUtil;
import com.szyt.basicframe.util.RedisUtil;
import com.szyt.basicframe.util.SecurityUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private RedisUtil redisUtil;

    @Before("@annotation(requiresPermissions)")
    public void before(RequiresPermissions requiresPermissions) {
        String[] permissions = requiresPermissions.value();
        Logical logical = requiresPermissions.logical();

        String redisKey = LoginUtil.getUserCacheKey(SecurityUtils.getCurrentUserId() + "");
        LoginUser loginUser = redisUtil.get(redisKey, LoginUser.class);
        List<String> userPermissions = loginUser.getPermissions();

        if (logical == Logical.AND) {
            for (String permission : permissions) {
                if (!userPermissions.contains(permission)) {
                    throw new AccessDeniedException("无权限访问");
                }
            }
        } else {
            boolean hasAny = false;
            for (String permission : permissions) {
                if (userPermissions.contains(permission)) {
                    hasAny = true;
                    break;
                }
            }
            if (!hasAny) {
                throw new AccessDeniedException("无权限访问");
            }
        }
    }
}

